package cn.bonoon.controllers;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.batatasframework.rawdata.RawdataDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.bonoon.core.RawdataImportService;
import cn.bonoon.core.RawdataStreamService;
import cn.bonoon.entities.RawdataImportEntity;
import cn.bonoon.entities.RawdataImportMaterial;
import cn.bonoon.kernel.annotations.QueryExpression;
import cn.bonoon.kernel.security.LogonUser;
import cn.bonoon.kernel.util.StringHelper;
import cn.bonoon.kernel.web.ButtonEventType;
import cn.bonoon.kernel.web.ButtonRefreshType;
import cn.bonoon.kernel.web.annotations.grid.GridStandardDefinition;
import cn.bonoon.kernel.web.controllers.AbstractGridController;
import cn.bonoon.kernel.web.models.JsonResult;

/**
 * 
 * 行业数据导入结果
 */
@Controller
@RequestMapping("s/rdi/{catalog}!result")
public class RawdataResultController extends AbstractGridController<RawdataImportEntity, RawdataImportItem> {

	@Autowired
	private RawdataImportService rawdataImportService;

	@Autowired
	private  RawdataStreamService rawdataStreamService;
	

	@Autowired
	public RawdataResultController(
			RawdataImportService rawdataImportService) {
		super(rawdataImportService);
		this.rawdataImportService = rawdataImportService;
	}

	@GridStandardDefinition(deleteOperation = false, autoOperation = true)
	@Override
	@QueryExpression("x.ownerId={USER owner} and x.deleted=0 ")
	protected RawdataImportService initLayoutGrid(LayoutGridRegister register)
			throws Exception {
		register.button("查看详情", "detail.dlg", ButtonEventType.DIALOG,
				ButtonRefreshType.FINISH);
		register.button("删除", "delete.do", ButtonEventType.GET,ButtonRefreshType.FINISH);
		register.button("切换状态", "changeforbid.do", ButtonEventType.GET, ButtonRefreshType.FINISH);
		register.button("导出Excel", "download.do", ButtonEventType.JUMP, ButtonRefreshType.FINISH);
		register.button("重新检查", "recheck.do", ButtonEventType.GET,ButtonRefreshType.FINISH);
		register.button("选择保障年度", "saveYear.dlg", ButtonEventType.DIALOG,
				ButtonRefreshType.FINISH).status(0);
		register.button("修改年度", "alterYear.dlg", ButtonEventType.DIALOG,
				ButtonRefreshType.FINISH).status(1);
		return rawdataImportService;
	}

	// 查看详情
	@RequestMapping("!{key}/detail.dlg")
	public String detail(Model model,@RequestParam("id") Long id,@RequestParam("gridid") String gridid,@PathVariable("key") String key) {
		model.addAttribute("layout", "layout-empty.vm");
		model.addAttribute("gridid", gridid);
		model.addAttribute("subject", id);
		RawdataImportEntity entity=rawdataImportService.get(id);
		model.addAttribute("entity",entity);
		
		List<RawdataImportMaterial> materials=entity.getMaterials();
		model.addAttribute("materials",materials);
		model.addAttribute("materialsSize", materials.size());

		LogonUser user = getUser();
		
		RawdataDefinition def = rawdataStreamService.getDefinition(user, entity.getCatalog(), entity.getKey());
		
		model.addAttribute("detailItemPath", def.getVmpath());
		
		List<Object> items=rawdataImportService.getItems(user, entity, def,true);
		
		//村级已处理记录数
		int handled=0;
		//村级导入月报成功数
		int success=0;
		//匹配成功
		int success2=0;
		//无法匹配
		int fail=0;
		//存疑 
		int doubt=0;
		//退回
		int back=0;
		//重复
		int repeat=0;
		
		for (Object object : items) {
			if (!"NONE".equals(StringHelper.getValueByFiled(object, "treatment").toString())) {
				handled++;
			}
			if ("TREATED".equals(StringHelper.getValueByFiled(object, "treatment").toString())) {
				success++;
			}
			//匹配成功
			else if (("UNTREATED".equals(StringHelper.getValueByFiled(object, "status").toString())&&"NONE".equals(StringHelper.getValueByFiled(object, "treatment").toString()))) {
				success2++;
			}
			//无法匹配
			else if ("ABNORMAL".equals(StringHelper.getValueByFiled(object, "status").toString())) {
				fail++;
			}
			//存疑
			else if ("DOUBTFUL".equals(StringHelper.getValueByFiled(object, "treatment").toString())) {
				doubt++;
			}
			//退回
			else if ("REJECT".equals(StringHelper.getValueByFiled(object, "treatment").toString())) {
				back++;
			}
			//重复
			else if ("REPEAT".equals(StringHelper.getValueByFiled(object, "treatment").toString())) {
				repeat++;
			}
			
		}
		
		model.addAttribute("success2",success2);
		model.addAttribute("fail",fail);
		model.addAttribute("doubt",doubt);
		model.addAttribute("back",back);
		model.addAttribute("repeat",repeat);
		
		
		model.addAttribute("result",true);
		model.addAttribute("success", success);
		model.addAttribute("handled", handled);
		model.addAttribute("items", items);
		model.addAttribute("size",items.size());
		model.addAttribute("selectable",false);
		model.addAttribute("haohaochi",def.getKey());
		return "plugs-rawdata/details";
	}

	
	/**
	 * 查看某一个导入结果的导入详情，把成功、无法匹配(包括身份证匹配不到，身份证匹配到了，姓名匹配不上的情况)、存疑、退回等分别显示
	 */
	@RequestMapping("!{key}/page.change")
	public String page2(@RequestParam("subject") Long id,int start,int end,String type,
			HttpServletRequest request, Model model) {
		RawdataImportEntity  entity = rawdataImportService.get(id);
		LogonUser user = getUser();
		RawdataDefinition def = rawdataStreamService.getDefinition(user, entity.getCatalog(), entity.getKey());
		List<Object> list=rawdataImportService.getItems(user, entity, def, false);
		List<Object> list2=rawdataImportService.getItemsByType(list,type).subList(start, end);
		model.addAttribute("items", list2);
		model.addAttribute("layout", "layout-empty.vm");
		return def.getVmpath();
	}
	
	//删除
	@ResponseBody
	@RequestMapping("!{key}/delete.do")
	public JsonResult change(@RequestParam("id") Long id) {
		try {
			RawdataImportEntity rawdataImport=rawdataImportService.get(id);
			RawdataDefinition def = rawdataStreamService.getDefinition(getUser(), rawdataImport.getCatalog(), rawdataImport.getKey());
			rawdataImportService.deleteByImportItem(rawdataImport, getUser(),def);
		} catch (Exception e) {
			return JsonResult.error(e);
		}
		return JsonResult.result();
	}
	
	//重新检查
	@ResponseBody
	@RequestMapping("!{key}/recheck.do")
	public JsonResult recheck(@RequestParam("id") Long id) {
		try {
			RawdataImportEntity rawdataImport=rawdataImportService.get(id);
			RawdataDefinition def = rawdataStreamService.getDefinition(getUser(), rawdataImport.getCatalog(), rawdataImport.getKey());
			rawdataImportService.recheck(rawdataImport, getUser(),def);
		} catch (Exception e) {
			return JsonResult.error(e);
		}
		return JsonResult.result();
	}
	
	//切换导入状态
	@ResponseBody
	@RequestMapping("!{key}/changeforbid.do")
	public JsonResult changeforbid(@RequestParam("id") Long id) {
		try {
			RawdataImportEntity rawdataImport=rawdataImportService.get(id);
			RawdataDefinition def = rawdataStreamService.getDefinition(getUser(), rawdataImport.getCatalog(), rawdataImport.getKey());
			rawdataImportService.changeforbid(getUser(),rawdataImport,def);
		} catch (Exception e) {
			return JsonResult.error(e);
		}
		return JsonResult.result();
	}
	
	//导出Excel
	@RequestMapping(value = "!{key}/download.do")
	public void download(HttpServletResponse response,
			HttpServletRequest request, 
			@RequestParam("id") Long id) {
		RawdataImportEntity entity=rawdataImportService.get(id);
		RawdataDefinition def = rawdataStreamService.getDefinition(getUser(), entity.getCatalog(), entity.getKey());		
		List<Object> items=rawdataImportService.getItems(getUser(), entity, def,true);
		String[] filename=entity.getName().split("\\.");
		String shellName =filename[0];
		def.getParser().excelFormat(items, response, request, shellName);
	}
	//填写保障年度
	@RequestMapping("!{key}/saveYear.dlg")
	public String saveYear(Model model,@RequestParam("id") Long id,@RequestParam("gridid") String gridid) {
		RawdataImportEntity entity=rawdataImportService.get(id);
		model.addAttribute("title", entity.getTitle());
		model.addAttribute("oid", id);
		model.addAttribute("condition", "saveYear");
		model.addAttribute("gridid", gridid);
		model.addAttribute("layout", "layout-empty.vm");
		return "plugs-rawdata/confirm";
			
	}
	//修改年度
	@RequestMapping("!{key}/alterYear.dlg")
	public String alterYear(Model model,@RequestParam("id") Long id,@RequestParam("gridid") String gridid) {
		RawdataImportEntity entity=rawdataImportService.get(id);
		model.addAttribute("title", entity.getTitle());
		model.addAttribute("insuredYear", entity.getInsuredYear());
		model.addAttribute("oid", id);
		model.addAttribute("condition", "alterYear");
		model.addAttribute("gridid", gridid);
		model.addAttribute("layout", "layout-empty.vm");
		return "plugs-rawdata/confirm";
		
	}
	@ResponseBody
	@RequestMapping("!{key}/save.do")
	public JsonResult save(@RequestParam("id") Long id,int insuredYear) {
		try {
			RawdataImportEntity rawdataImport=rawdataImportService.get(id);
			rawdataImport.setInsuredYear(insuredYear);
			rawdataImport.setInsuStatus(1);
			rawdataImportService.update(getUser(), rawdataImport);
		} catch (Exception e) {
			return JsonResult.error(e);
		}
		return JsonResult.result();
	}
	
}
